package com.wtp.wallpaper.aspect;

import com.wtp.wallpaper.annotation.RedisLimitAnnotation;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Aspect
@Component
public class RedisLimitAop {

    Object result = null;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private DefaultRedisScript<Long> redisLuaScript;

    @PostConstruct
    public void init(){
        redisLuaScript = new DefaultRedisScript<>();
        redisLuaScript.setResultType(Long.class);
        redisLuaScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("rateLimiter.lua")));
    }

    @Around("@annotation(com.wtp.wallpaper.annotation.RedisLimitAnnotation)" +
            "|| @within(com.wtp.wallpaper.annotation.ReplaceURL)")
    public Object around(ProceedingJoinPoint joinPoint){

        //方法签名
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();

        RedisLimitAnnotation redisLimitAnnotation = method.getAnnotation(RedisLimitAnnotation.class);
        if(redisLimitAnnotation != null){

            String key = redisLimitAnnotation.key();
            String className = method.getDeclaringClass().getName();
            String methodName = method.getName();

            //对当前key进行限流
            String limitKey = key + "\t" + className + "\t" + methodName;
            log.info(limitKey);

            if(key == null){
                throw new RuntimeException("key 为 null");
            }

            long limit = redisLimitAnnotation.permitsPerSecond();
            long expire = redisLimitAnnotation.expire();
            List<String> keys = new ArrayList<>();
            keys.add(key);

            Long count = stringRedisTemplate.execute(
                    redisLuaScript,
                    keys,
                    String.valueOf(limit),
                    String.valueOf(expire)
            );


            System.out.println("Access try count is "+count+" \t key= "+key);

            if(count != null && count == 0){
                System.out.println("启动限流功能key:" + key);
                return redisLimitAnnotation.msg();
            }
        }

        try {
            //放行
            result = joinPoint.proceed();
        }catch(Throwable e){
            throw new RuntimeException(e);
        }

        return result;
    }


}
